package com.cqhz.quwan.ui.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.v4.app.Fragment
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.alipay.sdk.app.AuthTask
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.LogUtils
import com.cqhz.quwan.APP
import com.cqhz.quwan.R
import com.cqhz.quwan.model.AlipayAuthData
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.mvp.IBasicView
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.util.*
import com.gyf.barlibrary.BarHide
import com.gyf.barlibrary.ImmersionBar
import me.militch.quickcore.util.ApiException


abstract class AbsFragment : Fragment(), IBasicView, AlipayContract.View {
    lateinit var rootView: View
    lateinit var loadingToast: LoadingToast
    private lateinit var aliPayHandler: AliPayHandler
    private val handler: Handler = Handler()
    var mImmersionBar: ImmersionBar? = null

    /**
     * 是否在Fragment使用沉浸式
     *
     * @return the boolean
     */
    open fun isImmersionBarEnabled(): Boolean {
        return true
    }

    /**
     * 初始化沉浸式
     */
    open fun initImmersionBar() {
        mImmersionBar!!.reset()
                .fitsSystemWindows(true)// 使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.colorPrimary)
                .init()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mImmersionBar = ImmersionBar.with(this)
        if (isImmersionBarEnabled()) {
            initImmersionBar()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && mImmersionBar != null) {
            initImmersionBar()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mImmersionBar != null) {
            mImmersionBar!!.destroy()
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Log.e("AbsFragment", "onCreateView")
        return inflater.inflate(layout(), container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        Log.e("AbsFragment", "onActivityCreated")
        aliPayHandler = AliPayHandler(this)
        loadingToast = LoadingToast.create(activity!!)
        initView()
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
    }

    override fun alipayAuthFail(authResult: AuthResult) {

    }

    override fun alipayCallBack() {

    }

    override fun alipayFail(payResult: PayResult) {

    }

    abstract fun layout(): Int
    abstract fun initView()
    override fun showToast(toast: String) {
        Toast.makeText(activity, toast, Toast.LENGTH_SHORT).show()
    }

    override fun toIntent(intent: Intent) {
        startActivity(intent)
    }

    override fun context(): Context {
        return activity!!
    }

    override fun showRequestError(e: ApiException) {
        hintLoading()
        LogUtils.e("ApiException", e.cause.toString())
        if (e.cause != null) {
            val t = e.cause
//            showToast("请求失败，请重试")
            return
        }
        showToast(e.message!!)
    }

    override fun toIntent(clazz: Class<*>) {
        startActivity(Intent(activity, clazz))
    }

    override fun closePage() {
        activity!!.finish()
    }

    override fun showLoading() {
        activity!!.runOnUiThread {
            showLoading(getString(R.string.label_loading))
        }
    }

    override fun showLoading(text: String) {
        activity!!.runOnUiThread {
            lockWindow(true)
            loadingToast.show(text)
        }
    }

    override fun hintLoading() {
        activity!!.runOnUiThread {
            lockWindow(false)
            if (loadingToast.showing()) {
                loadingToast.hint()
            }
        }
    }

    override fun callAlipay(arg: String) {
        val t = Thread({
            Looper.prepare()
            val payTask = PayTask(activity)
            val result = payTask.payV2(arg, true)
            val msg = Message()
            msg.what = AliPayHandler.ALIPAY_PAY_FLAG
            msg.obj = result
            aliPayHandler.handleMessage(msg)
            Looper.loop()
        })
        t.start()
    }

    override fun callAlipayAuth(arg: String) {
        val t = Thread({
            Looper.prepare()
            val at = AuthTask(activity)
            val result = at.authV2(arg, true)
            val msg = Message()
            msg.what = AliPayHandler.ALIPAY_AUTH_FLAG
            msg.obj = result
            aliPayHandler.handleMessage(msg)
            Looper.loop()
        })
        t.start()
    }

    fun getLogin(): LoginBean? {
        return APP.get()!!.loginInfo
    }

    fun getUserId(): String {
        return if (getLogin() == null) {
            ""
        } else {
            if (TextUtils.isEmpty(getLogin()!!.userId)) {
                ""
            } else {
                getLogin()!!.userId!!
            }
        }
    }

    fun checkLogin(): Boolean {
        return if (TextUtils.isEmpty(getUserId())) {
            toIntent(LoginActivity::class.java)
            false
        } else {
            true
        }
    }
}